package br.com.afi.util.hibernate.validator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Classe que verifica se a String é uma data no futuro válida.
 * 
 * @author André de Fontana Ignacio
 * @version 1.0
 */
public class FutureStrValidator implements ConstraintValidator<FutureStr,String>
{
	private String pattern;
	private String language;
	private String country;
	private boolean exactMatch;

	@Override
	public void initialize( FutureStr parameters )
	{
		this.pattern = parameters.pattern();
		this.language = parameters.language();
		this.country = parameters.country();
		this.exactMatch = parameters.exactMatch();
	}

	@Override
	public boolean isValid( String value, ConstraintValidatorContext constraintContext )
	{
		if ( value == null )
		{
			return true;
		}
		if ( value.isEmpty() )
		{
			return true;
		}
		Locale locale = null;
		if ( !language.isEmpty() || !country.isEmpty() )
		{
			locale = new Locale( language, country );
		}
		else
		{
			locale = Locale.getDefault();
		}
		final SimpleDateFormat sdf = new SimpleDateFormat( pattern, locale );
		sdf.setLenient( exactMatch );
		try
		{
			final Date date = sdf.parse( value );
			if ( exactMatch && pattern.length() != value.length() )
			{
				return false;
			}
			if ( !date.after( new Date() ) )
			{
				return false;
			}
		}
		catch ( ParseException e )
		{
			return false;
		}
		return true;
	}
}
